package com.pattern.proxy.Jdk;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class GPClassLoader extends ClassLoader {
    private File classPathFile;

    public GPClassLoader(){
        String path = GPClassLoader.class.getResource("").getPath();
        this.classPathFile= new File(path);
    }

    protected Class<?> findClass(String name)throws ClassNotFoundException{
        String className= GPClassLoader.class.getPackage().getName() +"."+name;//获取包名 加文件名
        if(classPathFile!=null){
            File classFile = new File(classPathFile, name.replaceAll("\\.", "/") + ".class");
            if(classPathFile.exists()){
                FileInputStream fis=null;
                ByteArrayOutputStream out=null;

                try {
                    fis =new FileInputStream(classFile);
                    out = new ByteArrayOutputStream();
                    byte[] buff = new byte[1024];
                    int len;
                    while ((len=fis.read(buff))!=-1){
                        out.write(buff,0,len);
                    }
                    return defineClass(className,out.toByteArray(),0,out.size());
                }catch (Exception e){
                    e.printStackTrace();
                }/*finally {
                    if(null != fis){
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if(out != null){
                        try {out.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }*/
            }
        }

        return null;
    }
}
